package com.topboya.linker.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.topboya.linker.AppConst;
import com.topboya.linker.R;
import com.topboya.linker.diyview.DeleteTaskDialog;
import com.topboya.linker.diyview.MyRelativeLayout;
import com.topboya.linker.diyview.NoDeleteTaskDialog;
import com.topboya.linker.model.levelitem.DepartmentGroup;
import com.topboya.linker.model.levelitem.DepartmentGroupBo;
import com.topboya.linker.model.response.DeptUserResponse;
import com.topboya.linker.model.response.HomeListResponse;
import com.topboya.linker.ui.activity.FeedbackAndDetailActitivy;
import com.topboya.linker.ui.activity.SelectTeamActivity;
import com.topboya.linker.ui.activity.xMainActivity;
import com.topboya.linker.ui.activity.xSelectTeamActivity;
import com.topboya.linker.ui.adapter.DepartMemberAdapter;
import com.topboya.linker.ui.adapter.HomeList1Adapter;
import com.topboya.linker.ui.adapter.RecycleViewDivider;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.ui.base.fragment.BaseFragment;
import com.topboya.linker.ui.presenter.HomePresenter;
import com.topboya.linker.ui.view.HomeView;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.UIUtils;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeFragment extends BaseFragment<HomeView,HomePresenter> implements HomeView,CalendarView.OnCalendarSelectListener,
        CalendarView.OnYearChangeListener,TencentLocationListener {
    private static final String TAG = "HomeFragment:";
    private TextView tv_date;
    private CalendarView mCalendarView;
    private RecyclerView rl_home_task;
    private MyRelativeLayout myrel_rootview;
    private RelativeLayout rel_top;
    private RecyclerView rl_depart_member;
    private CalendarLayout calendarLayout;
    private LinearLayout ll_select_member;
    private TextView tv_select_member;
    private TextView tv_today;
    private int year;
    private int month;
    private int day;
    private xMainActivity xmainActivity;
//    private HomeListAdapter homelistadapter;
    private HomeList1Adapter homelistadapter1;
    private HomePresenter homePresenter;
    private  List<DepartmentGroupBo> departmentGroupBos;
//    点击签到的ID
    private String orgID;
    private List<DeptUserResponse.Data> mData;
    private DepartMemberAdapter departMemberAdapter;
    private boolean isMyTask =true;


    @Override
    protected int getLayoutId() {

        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {

        tv_date = mRootView.findViewById(R.id.tv_date);
        mCalendarView = mRootView.findViewById(R.id.calendarView);
        mCalendarView.setOnYearChangeListener(this);
        mCalendarView.setOnCalendarSelectListener(this);
        rl_home_task = mRootView.findViewById(R.id.rl_home_task);
        rel_top = mRootView.findViewById(R.id.rel_top);
        rl_depart_member = mRootView.findViewById(R.id.rl_depart_member);
        calendarLayout = mRootView.findViewById(R.id.calendarLayout);
//        myrel_rootview = mRootView.findViewById(R.id.myrel_rootview);
        ll_select_member = mRootView.findViewById(R.id.ll_select_member);
        tv_select_member = mRootView.findViewById(R.id.tv_select_member);
        tv_today = mRootView.findViewById(R.id.tv_today);
//        myrel_rootview.setChild(getContext(),rel_top,rl_depart_member,calendarLayout);
        calendarLayout.setTopViewVisibleListener(() -> {

           LogUtils.v(TAG+"isVisible()");
        });

    }

    @Override
    public void initListener() {
//        calendarLayout.setTopViewVisibleListener(() -> {UIUtils.showToast("显示回调"); });
        tv_today.setOnClickListener(v -> { mCalendarView.scrollToCurrent(); });
        xmainActivity.setOnTeamBtnClickListener((ismytask) -> {
            LogUtils.v(TAG + "ismytask:"+ismytask);
            isMyTask = ismytask;
//            弹出选择人员布局
            if (ismytask){

                rel_top.setVisibility(View.GONE);
                calendarLayout.isTeam(false);
                JSONArray jsonArray = new JSONArray();
                try {
                    jsonArray.put(0,AppConst.USERID);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mPresenter.getLocationFromTencent(year+"-"+ String.format("%02d", month)+"-"+String.format("%02d", day),jsonArray.toString());


            }else {
                rel_top.setVisibility(View.VISIBLE);
                calendarLayout.isTeam(true);
                getMemberTask();

            }
        });
        homelistadapter1.setOnItemClickListener((v, position) ->{

            Intent intent = new Intent(mContext,FeedbackAndDetailActitivy.class);
            intent.putExtra("isfeedback",false);
            intent.putExtra("taskLists",taskLists.get(position));
            startActivity(intent);

        } );
        homelistadapter1.setOnItemLongClickListener((v, position) -> itemLongClick(position));
//0:不能签入 1:可签入 2:已签入可迁出 3:已签入超过三公里 4：正常签出 5：非正常签出 6：非正常签出
        homelistadapter1.setOnitemChildCkickListener((view, position) -> {

                             //  获取点击签到的终端医院id
                     orgID = taskLists.get(position).getOrgId();
                     String status = taskLists.get(position).getStatus();
//                     表示可以签入，就进行签到
                     if ("1".equals(status)) {
                         getLocationFromTencent();
                     }else if ("2".equals(status) || "3".equals(status)){
//                         进入任务反馈页面，进行签出
                         Intent intent = new Intent(mContext,FeedbackAndDetailActitivy.class);
                         intent.putExtra("isfeedback",true);
                         intent.putExtra("taskLists",taskLists.get(position));
                         startActivityForResult(intent,1002);

                     }
        });
        ll_select_member.setOnClickListener(v -> {

            mData = xmainActivity.getmData();
            Intent intent = new Intent(xmainActivity,xSelectTeamActivity.class);
            intent.putExtra("mData", (Serializable) mData);
            startActivityForResult(intent,1001);

        });
        departMemberAdapter.setOnitemChildCkickListener((view, position) -> {

//            点击删除按钮 ，删除数据，刷新ui，重新请求数据

               AppConst.SELECTED_MEMBER.remove(departmentGroupBos.get(position));
               departmentGroupBos.remove(position);
               LogUtils.v(TAG + "departmentGroupBos:"+departmentGroupBos.toString());
               departMemberAdapter.notifyDataSetChanged();
               getMemberTask();

        });

        xmainActivity.SetOnrefreshMemberListener(() -> {

            if (null !=departmentGroupBos){
                this.departmentGroupBos.clear();
                this.departmentGroupBos.addAll(AppConst.SELECTED_MEMBER);
                departMemberAdapter.notifyDataSetChanged();
                getMemberTask();
            }


        });
    }

    private void getMemberTask() {

        JSONArray jsonArray = new JSONArray();

      for (int i=0;i< departmentGroupBos.size();i++){
          try {
              jsonArray.put(i,departmentGroupBos.get(i).getMemberID());
              LogUtils.v(TAG +"i--:"+i+"result_rememberid:"+departmentGroupBos.get(i).getMemberID());
          } catch (JSONException e) {
              e.printStackTrace();
          }
      }
      mPresenter.getLocationFromTencent(year+"-"+ String.format("%02d", month)+"-"+String.format("%02d", day),jsonArray.toString());

    }

    //    点击签到状态按钮
    @Override
    protected void initData() {

       LogUtils.v(TAG+"initData()-----");
        xmainActivity  = (xMainActivity) getActivity();
        taskLists = new ArrayList<>();
//        homelistadapter = new HomeListAdapter(mainActivity,homePresenter,taskLists);
//        rl_home_task.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, 2, 0xBFC0C2));
        homelistadapter1 = new HomeList1Adapter(xmainActivity,homePresenter,taskLists);
        rl_home_task.setAdapter(homelistadapter1);

        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rl_depart_member.setLayoutManager(manager);
        departmentGroupBos = new ArrayList<>();
        departMemberAdapter = new DepartMemberAdapter(departmentGroupBos);
        rl_depart_member.setAdapter(departMemberAdapter);

    }


    @Override
    protected HomePresenter createPresenter() {
        homePresenter = new HomePresenter((BaseActivity) getActivity());

        return homePresenter;
    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        return calendar;
    }

    @Override
    public void getDayByYeahMonth(List<String> dayByYearMothList) {

         LogUtils.v(TAG + "dayByYearMothList:"+dayByYearMothList.toString());
        Map<String, Calendar> map = new HashMap<>();

        for (int i=0;i < dayByYearMothList.size();i++){
            int taskday =  Integer.parseInt(dayByYearMothList.get(i));
            map.put(getSchemeCalendar(year, month, taskday, 0xFF008577, "假").toString(),
                    getSchemeCalendar(year, month, taskday , 0xFF008577, "假"));
        }

        //此方法在巨大的数据量上不影响遍历性能，推荐使用
        mCalendarView.setSchemeDate(map);


    }
    List<HomeListResponse.TaskList> taskLists;
    @Override
    public void getHomeList(HomeListResponse homeListResponse) {
        LogUtils.v(TAG + "getHomeList()");

        LogUtils.v(TAG + homeListResponse.toString());
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext,
                LinearLayoutManager.VERTICAL, false);
        rl_home_task.setLayoutManager(layoutManager);

        taskLists.clear();
        taskLists.addAll(homeListResponse.getData().getList());
        homelistadapter1.notifyDataSetChanged();
//        homelistadapter.setOnItemLongClickListener((adapter, view, position) ->{ itemLongClick(position);return false; });

    }

//    删除任务返回的结果
    @Override
    public void DeleteTaskResult() {

        UIUtils.showToast("删除任务成功");
        JSONArray jsonArray = new JSONArray();
        LogUtils.v(TAG+"yeah:"+year+",month:"+month+",day:"+day);

        try {
            jsonArray.put(0,AppConst.USERID);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        mPresenter.getLocationFromTencent(year+"-"+ String.format("%02d", month)+"-"+String.format("%02d", day),jsonArray.toString());

    }

    @Override
    public void miniSignInResult() {

        // 返回签到结果
        UIUtils.showToast("签到成功");
//        homelistadapter1.notifyDataSetChanged();
        if (isMyTask){

            rel_top.setVisibility(View.GONE);
            calendarLayout.isTeam(false);
            JSONArray jsonArray = new JSONArray();
            try {
                jsonArray.put(0,AppConst.USERID);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            mPresenter.getLocationFromTencent(year+"-"+ String.format("%02d", month)+"-"+String.format("%02d", day),jsonArray.toString());


        }else {
            rel_top.setVisibility(View.VISIBLE);
            calendarLayout.isTeam(true);
            getMemberTask();

        }
    }

    @Override
    public void onYearChange(int year) {

        this.year =year;
        LogUtils.v(TAG + "onYearChange:"+year);
    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

        Toast.makeText(getContext(),"onCalendarOutOfRange:",Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {

        LogUtils.v(TAG +"onCalendarSelect()");
        year = calendar.getYear();
        month = calendar.getMonth();
        day = calendar.getDay();
        LogUtils.v(TAG+"yeah:"+year+",month:"+month+",day:"+day);
        tv_date.setText(year +"年"+month+"月");
        JSONArray jsonArray = new JSONArray();

        try {

            jsonArray.put(0,AppConst.USERID);

        } catch (JSONException e) {

            e.printStackTrace();
        }

        if (!isClick){
//            没有点击具体哪一天，只查询月份，默认显示每一月一号的任务列表
            mPresenter.getDayByYearMoth(year+"-"+ String.format("%02d", month));
            mPresenter.getLocationFromTencent(year+"-"+ String.format("%02d", month)+"-"+String.format("%02d", day),jsonArray.toString());

        }else {
            LogUtils.v(TAG + "isMyTask:"+isMyTask);

            if (!isMyTask){
//                显示团队的任务列表
                getMemberTask();

            }else {
                LogUtils.v(TAG + "ELSE");
                //   具体显示某一天的任务列表
                mPresenter.getLocationFromTencent(year+"-"+ String.format("%02d", month)+"-"+String.format("%02d", day),jsonArray.toString());

            }
        }
    }

 //0:不能签入
//1:可签入
//2:已签入可迁出
//3:已签入超过三公里
//4：正常签出
//5：非正常签出
//6：非正常签出
    private void itemLongClick(int position) {

//            判断时间是否超过现在，用long比较
        long currentime =   System.currentTimeMillis();
        long startime = getTimeLong(taskLists.get(position).getStartTime());
        LogUtils.v(TAG + "currentime:"+currentime+",startime:"+startime);
        if ((currentime -startime) < 0 || taskLists.get(position).getStatus().equals("1")){
//          可以删除
            showDeleteTaskDialog(position);

        }else {

            showNoDeleteTaskDialog();
        }
    }
    private void showDeleteTaskDialog(int position){

        final DeleteTaskDialog deleteTaskDialog = DeleteTaskDialog.newInstance();
        deleteTaskDialog.show(xmainActivity.getFragmentManager(), "order");
        deleteTaskDialog.setCancelable(false);
        deleteTaskDialog.setSureButtonListener(v -> {

            homePresenter.deleteTask(taskLists.get(position).getId());
            deleteTaskDialog.dismiss();
        });
        deleteTaskDialog.setCancleButtonListener(v -> deleteTaskDialog.dismiss());
    }

    private void showNoDeleteTaskDialog(){

        final NoDeleteTaskDialog noDeleteTaskDialog = NoDeleteTaskDialog.newInstance();
        noDeleteTaskDialog.show(xmainActivity.getFragmentManager(), "order");
        noDeleteTaskDialog.setCancelable(false);
        noDeleteTaskDialog.setCloseButtonListener(v ->  noDeleteTaskDialog.dismiss());

    }


    private long getTimeLong(String time){

        long lasttime =0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date date = sdf.parse(time);
            lasttime =  date.getTime();

            return lasttime;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return 0;
    }


    //    签到获取实时地理位置
    public void getLocationFromTencent(){

        TencentLocationRequest request = TencentLocationRequest.create();
        request.setInterval(24*60*60*1000);
        request.setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_NAME);
        request.setAllowCache(true);
        TencentLocationManager locationManager = TencentLocationManager.getInstance(mContext);
        int erro = locationManager.requestLocationUpdates(request, this);
        Log.v(TAG,"tencent_map_error:"+erro);

    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {

        LogUtils.v(TAG + "tencentLocation"+ tencentLocation.toString());
        LogUtils.v(TAG + "latitude:"+ tencentLocation.getLatitude() +"longitude:"+ tencentLocation.getLongitude());
        String latitude = String.valueOf(tencentLocation.getLatitude());
        String longitude = String.valueOf(tencentLocation.getLongitude());
         mPresenter.miniSignIn("","",latitude,longitude,orgID);


    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//      在这里设置选择人员的list,如果list不为空，说明有数据，则设置adapter
        LogUtils.v(TAG + "resultCode---------"+resultCode);
        if (null !=data){

//           刷新显示的adapter，然后在请求任务
            this.departmentGroupBos.clear();
            this.departmentGroupBos.addAll(AppConst.SELECTED_MEMBER);
            departMemberAdapter.notifyDataSetChanged();
            getMemberTask();

        }

    }




}
